package com.horoscope.astrology.zodiac.signs.free.utils

import android.app.Activity
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.util.Log
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.horoscope.astrology.zodiac.signs.free.MmoApplication
import com.horoscope.astrology.zodiac.signs.free.R

//https://www.jianshu.com/p/e78407a18716
object ImageLoader {
    fun loadImage(imageView: ImageView, url: String?) {
        if (url == null) return
        Glide.with(MmoApplication.getInstance().applicationContext)
            .asBitmap()
            .apply(getRequestOptions()).load(url)
            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
            .into(imageView)
    }

    fun loadImageForWidth(imageView: ImageView, url: String?, width: Int, height: Int) {
        if (url == null) return
        Glide.with(MmoApplication.getInstance().applicationContext)
            .asBitmap()
            .apply(getRequestOptions()).load(url)
            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
            .override(width, height)
            .thumbnail(0.1f)
            .into(imageView)
    }

    fun loadLocalImage(imageView: ImageView, resId: Int) {
        Glide.with(MmoApplication.getInstance().applicationContext).load(resId).into(imageView)
    }


    fun loadBitmap(context: Activity, imageView: ImageView, bitmap: Bitmap) {
        if (!context.isDestroyed) {
            val drawable = BitmapDrawable(null, bitmap)
            Glide.with(context)
                .load(drawable)
                .apply(getRequestOptions())
                .into(imageView)
        } else {
            Log.d("Glide", "activity is destory")
        }
    }

    fun loadGifImage(imageView: ImageView, resId: Int) {
        Glide.with(MmoApplication.getInstance().applicationContext)
            .asGif()
            .load(resId)
            .apply(getRequestOptions())
            .into(imageView)
    }

    /**
     * @param placeholder 占位图
     * @param error 失败图
     * @param priority 下载优先级
     */
    private fun getRequestOptions(): RequestOptions {
        return RequestOptions()
            .placeholder(R.mipmap.placeholder)
            .error(R.mipmap.placeholder)
            .priority(Priority.HIGH)
    }


}